﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using JoyfulHomeJourney.BackEnd.Infrastructure.Atrributes;
using JoyfulHomeJourney.BackEnd.Infrastructure.Dtos.Requests;
using JoyfulHomeJourney.BackEnd.Infrastructure.Dtos.Responses;
using JoyfulHomeJourney.BackEnd.Infrastructure.EFCore;
using JoyfulHomeJourney.BackEnd.Infrastructure.Tools;
using JoyfulHomeJourney.BackEnd.Server.EFCore;
using JoyfulHomeJourney.BackEnd.Server.Interfaces;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.Extensions.Configuration;

namespace JoyfulHomeJourney.BackEnd.Server.Instances
{
    internal class LoginEF
    {
        public SysAccountsServerEF accountServerEF { get; set; }
        public LoginLogsServerEF loginLogServerEF { get; set; }
        public ShiftsServerEF shiftsServerEF { get; set; }
        public EmployeesServerEF employeesServerEF { get; set; }
    }
    [InjectClass]
    public class LoginServer : ILoginServer
    {
        private readonly IConfiguration _configuration;
        private readonly LoginEF _loginEF;

        public LoginServer(IConfiguration configuration, DbContext dbContext)
        {
            _configuration = configuration;
            _loginEF = new LoginEF
            {
                
                accountServerEF = new SysAccountsServerEF(dbContext),
                loginLogServerEF = new LoginLogsServerEF(dbContext),
                shiftsServerEF = new ShiftsServerEF(dbContext),
                employeesServerEF = new EmployeesServerEF(dbContext),
            };
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ResponseApiDto> LoginAsync(RequestLoginDto dto,string role)
        {
            SysAccounts account = await _loginEF.accountServerEF.Query(d => d.AAccount == dto.account&&d.ARole==role).SingleOrDefaultAsync();
            bool isLogin = false;
            object data = null;
            if (account != null)
            {
                if (account.AIsBan == 1)
                {
                    return ResponseApiDto.Fail("该账号已被禁用");
                }
                string encryptPwd = Encrypt.GetMd5Hash(dto.password + account.ASalt);
                if (account.APassword == encryptPwd)
                {
                    isLogin = true;
                    string code = Tools.Guid_1();
                  await  _loginEF.loginLogServerEF.AddAsync(new LoginLogs()
                    {
                        LlId = Tools.Guid_2(),
                        LlAdminId = account.AId,
                        LlCode = code
                    });
                    // 配置JWT参数
                    var settings = new JwtSettings
                    {
                        SecretKey = Convert.ToBase64String(Encoding.UTF8.GetBytes(_configuration["JWT:secret"])), // 示例随机密钥
                        Issuer = _configuration["JWT:issuer"],
                        Audience = _configuration["JWT:audience"],
                        ExpireMinutes = 60*24*7
                    };

                    // 创建工具实例
                    var jwtHelper = new JwtHelper(settings);

                    // 创建payload对象
                    var user = new { aid = account.AId, code = code, role = account.ARole };

                    // 生成Token
                    data = new { token = jwtHelper.CreateToken(user) };

                    if (role== "employee")
                    {
                        string emid =await _loginEF.employeesServerEF.Query(d => d.EAccountId == account.AId).Select(d => d.EId).FirstOrDefaultAsync();
                        Shifts shifts = new Shifts
                        {
                            EEmployeeId = emid,
                            EStartTime = DateTime.Now,
                            EEndTime=null,
                            ECashRegisterId=0,
                            ENumberOfTransactions = 0,
                            ETotalAmount = 0,
                            ERemark=null,
                        };
                        await _loginEF.shiftsServerEF.AddAsync(shifts);
                    }
                }
            }
            return ResponseApiDto.Create(isLogin, "登录成功", "账号或密码错误", data);
        }
        /// <summary>
        /// 检查是否登录
        /// </summary>
        /// <param name="aid"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        public SysAccounts CheckLogin(string aid, string code)
        {
            LoginLogs log = _loginEF.loginLogServerEF.Query(d => d.LlAdminId == aid, false, d => d.LlCreateTime).FirstOrDefault();
            if (log != null && log.LlCode == code)
            {
                return _loginEF.accountServerEF.Query(d => d.AId == aid).SingleOrDefault();
            }
            else
            {
                return null;
            }
        }


        /// <summary>
        /// 获取所有员工账号信息
        /// </summary>
        /// <returns></returns>
        public async Task<ResponseApiDto> Get_employ()
        {
            var data = await _loginEF.accountServerEF.Query(d => d.ARole == "employee").Select(d => new 
            {
                name=d.AName,
                id=d.AId,
            }).ToListAsync();

            return ResponseApiDto.Success("数据已获取", new ResponsePaginationDto { data = data });
        }
    }
}